<template>
  <div class="box" style="width:60%;margin: 0 auto">
    <div id="container" style="width:100%; height:600px;margin: 0 auto">
    </div>
    <div id="panel"></div>
    <div class="toolbar">
      <button @click="delMark()">删除标记</button>
      <button @click="driving()">路线规划</button>
      <button @click="clear()">清空规划</button>
      <button @click="dragRouteDriving()">拖拽导航</button>
    </div>
  </div>

</template>

<script>
  import AMap from 'AMap' // 引入高德地图

  export default {
    data(){
      return{
        map:'',//当前地图实例
        markers:[],//标记点集合
        // driving: '',//驾车导航实例
        originSpot: '',//起点
        destinationSpot: '',//终点
        geolocation: '',
        drivings:[],
        dragRoutes:[],
      }
    },
    created() {

    },
    mounted () {
      this.init()
    },
    methods: {
      init () {
        this.map = new AMap.Map('container', {
          resizeEnable: true,//可自动调节窗口
          center: [121.63475230336189, 31.208965887409562],//该map实例的中心点位置
          zoom: 13,//初始地图比例
          viewMode:'3D',//使用3D视图
        });
        let map = this.map;//将map赋值给本地变量,方便再次使用
        // 插件控制中心
        AMap.plugin(['AMap.ToolBar',"AMap.Driving","AMap.Scale","AMap.HawkEye","AMap.MapType","AMap.Geolocation",'AMap.Geolocation'],()=>{//异步加载插件
          map.addControl(new AMap.ToolBar({
            position: {
              left: '20px',
              bottom: '200px'
            }}));//创建地图缩放控件
          // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
          map.addControl(new AMap.Scale());

          // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
          map.addControl(new AMap.HawkEye({isOpen:true}));

          // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
          map.addControl(new AMap.MapType());



          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
            buttonOffset: new AMap.Pixel(10, 20),
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            buttonPosition: 'RB'
          })

          map.addControl(geolocation);

        });
        //罗盘控件
        AMap.plugin([
          'AMap.ControlBar',
        ], function(){
          // 添加 3D 罗盘控制
          map.addControl(new AMap.ControlBar({
            position: {
              left: '20px',
              top: '20px'
            },
            showControlButton: true,  // 是否显示倾斜、旋转按钮。默认为 true
          }));
        });
        //室内地图

        //创建一个信息弹出框
        var infoWindow = new AMap.InfoWindow({
          isCustome:true,//使用自定义弹出窗体
          content:'<div><h2>蜗牛创想</h2><h3>互联网人才培养基地</h3> </div>',//弹出框内容,自定义
          offset: new AMap.Pixel(16, -45)//弹出框相对标记地点的偏移位置
        });

        var onMarkerClick = function (e) {
          infoWindow.open(map,e.target.getPosition());//在地图上相应位置打开弹出框,e.target代表点击的标记,getPosition获取位置
        }

        //创建标记右键菜单
        var markerMenu = new AMap.ContextMenu();
        var currentMarker;
        //定义标记点击事件
        var markerRightClick = function (e) {
          markerMenu.open(map,e.target.getPosition());
          currentMarker = this;
        }

        //右键点击删除标记
        markerMenu.addItem("删除标记", (e) => {
          map.remove(currentMarker);
        }, 1);

        //右键点击设为起点
        markerMenu.addItem("设为起点",  (e) => {
          this.originSpot = currentMarker;
        }, 2);

        //右键点击设为终点
        markerMenu.addItem("设为终点", (marker) => {
          this.destinationSpot = currentMarker;
        }, 3);

        //创建地图右键菜单
        var contextMenuPositon;
        var contextMenu = new AMap.ContextMenu();

        //定义地图右键点击事件
        var onRightClick = function (e) {
          contextMenu.open(map, e.lnglat);
          contextMenuPositon = e.lnglat;
        }

        //右键点击添加至标记
        contextMenu.addItem("添加标记", (e) => {
          var marker = new AMap.Marker({
            map: map,
            position: contextMenuPositon //基点位置
          });
          marker.on('rightclick', markerRightClick);
          this.markers.push(marker);
        }, 1);

        //设置起点大小
        var startIcon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(50, 60),
          // 图标的取图地址
          image: '//a.amap.com/jsapi/static/image/plugin/marker/start.png',
          // 图标所用图片大小
          imageSize: new AMap.Size(25, 30),
          // 图标取图偏移量
          imageOffset: new AMap.Pixel(12, 30)
        });

        //右键点击设为起点
        contextMenu.addItem("设为起点",  (e) => {
          var marker = new AMap.Marker({
            map: map,
            position: contextMenuPositon,//基点位置
            offset: new AMap.Pixel(-25, -60),
            icon: startIcon,
          });
          if(this.originSpot != ''){
            map.remove(this.originSpot);
          }
          marker.on('rightclick', markerRightClick);
          this.originSpot = marker;
        }, 2);


        var endIcon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(50, 60),
          // 图标的取图地址
          image: '//a.amap.com/jsapi/static/image/plugin/marker/end.png',
          // 图标所用图片大小
          imageSize: new AMap.Size(25, 30),
          // 图标取图偏移量
          imageOffset: new AMap.Pixel(12, 30)
        });

        //右键点击设为终点
        contextMenu.addItem("设为终点", (e) => {
          var marker = new AMap.Marker({
            map: map,
            position: contextMenuPositon,//基点位置
            offset: new AMap.Pixel(-25, -60),
            icon: endIcon
          });
          if(this.destinationSpot != ''){
            map.remove(this.destinationSpot);
          }
          marker.on('rightclick', markerRightClick);
          this.destinationSpot = marker;
        }, 3);


        //创建一个初始标记点
        var marker = new AMap.Marker({
          position:[121.63475230336189, 31.208965887409562]//创建一个初始标记点,点的位置为经纬度坐标
        });

        marker.on('click',onMarkerClick)//将标记点与点击事件绑定起来,才能弹出信息弹出框
        marker.on('rightclick', markerRightClick)
        map.add(marker);//将标记点添加进map


        //创建交通情况的实例
        var trafficLayer = new AMap.TileLayer.Traffic({
          zIndex: 10//图层深度
        });
        map.add(trafficLayer);//将交通情况图层添加进map

        //地图右键点击事件
        map.on('rightclick', onRightClick);

      },

      //删除最近的标记点
      delMark() {
        if(this.markers.length != 0){//如果存在标记点
          var marker = this.markers.pop();//弹栈,获取最后添加的标记点
          this.map.remove(marker);//移除该标记点
        }else{
          alert("你还未添加任何标记点");
        }
      },



      //驾车路线规划
      driving(){
        if (this.originSpot == '' ){
          alert("请先输入起点");
        }else if(this.destinationSpot == ''){
          alert("请输入终点");
        }else{
          var driving = new AMap.Driving({
            map: this.map,//获取当前地图实力
            panel: "panel"//获取导航信息的填充的面板
          });
          // 根据起终点经纬度规划驾车导航路线,第一个点为起点,第二个点为终点
          let search = driving.search(this.originSpot._position, this.destinationSpot._position, function(status, result) {
            // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
              console.log('绘制驾车路线完成')
            } else {
              console.log('绘制驾车路线失败' + result)
            }
          });
          this.drivings.push(driving);
        }
      },

      dragRouteDriving(){
        let map = this.map;
        if (this.originSpot == '' ){
          alert("请先输入起点");
        }else if(this.destinationSpot == ''){
          alert("请输入终点");
        }else {
          var path = [];
          path.push(this.originSpot._position);
          path.push(this.destinationSpot._position);
          map.plugin("AMap.DragRoute", ()=> {
            let route = new AMap.DragRoute(map, path, AMap.DrivingPolicy.LEAST_FEE); //构造拖拽导航类
            route.setPanel = "panel";
            route.search(); //查询导航路径并开启拖拽导航
            this.drivings.push(route);
            alert(1)
            map.remove(route)
          });
        }
      },

      clear(){
        // document.getElementById("panel").innerHTML=""
        this.map.remove(this.drivings.pop())
      }
    },
  }
</script>
<style>
  @import "https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css";
  #panel {
    position: fixed;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 10px;
    right: 10px;
    width: 280px;
  }
  #panel .amap-call {
    background-color: #009cf9;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }
  #panel .amap-lib-driving {
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    overflow: hidden;
  }
</style>
